package com.lee.boot.head.first.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sql.DataSource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    DataSource dataSource;

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        String queryUserSql = "select user_name, pwd,available from user where user_name = ?";
        String queryRoleSql = "select u.user_name ,r.role_name from " +
                "user as u right join r_user_role as rur on u.id = rur.user_id " +
                "left join role as r on rur.role_id = r.id " +
                "where u.user_name = ?";
//      super.configure(auth);
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//        auth.inMemoryAuthentication().passwordEncoder(passwordEncoder).withUser("user")
//                .password(passwordEncoder.encode("abc"))
//                .roles("users", "admin");
//        auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder)
//                .usersByUsernameQuery(queryUserSql)
//                .authoritiesByUsernameQuery(queryRoleSql);
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        // authorizeRequests方法是限定签名成功的用户请求
        // anyRequest方法是限定所有请求
        // authenticated 方法表示对所有签名的用户通过
        http.authorizeRequests().anyRequest().authenticated()
                .and().formLogin()
                // httpBasic方法表示启用http基础验证
                .and().httpBasic().realmName("你好");


    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }



}
